const Koa = require('koa'); // koa
const app = new Koa(); // 实例
const router = require('@koa/router')() // 路由
const bodyParser = require('koa-bodyparser'); // 接收post传参
const cors = require('koa-cors') // 解决跨域
const svgCaptcha = require('svg-captcha') // 验证码
const global = require('./utils/mysql') // 数据库
const jwt = require('jsonwebtoken') // 生成token

let captchas = " ";

// 验证码
router.get('/getcaptcha', async ctx => {
    var captcha = svgCaptcha.create({
        size: 4,
        noise: 5,
        color: true,
        background: "#fff",
        width: 100,
        height: 25,
        fontSize: 40
    });
    captchas = captcha.text;
    ctx.response.type = 'svg';
    ctx.body = captcha.data;
})

// 登录
router.post('/login', async ctx => {
    let { name, pwd, captcha } = ctx.request.body; // 获取参数

    // 判断用户是否存在
    let result = await global.query(`select * from user where name = '${name}'`)
    console.log(result);
    if (result.length == 0) {
        ctx.body = {
            code: 1,
            msg: '用户不存在 请先注册！'
        }
        return;
    }

    // 判断密码是否正确
    let results = await global.query(`select * from user where pwd = '${pwd}'`)
    if (results.length == 0) {
        ctx.body = {
            code: 2,
            msg: '密码不正确！'
        }
        return;
    }

    // 验证验证码是否正确，如果错误，则返回错误信息。 如果正确，则执行登录
    if (captcha.toUpperCase() != captchas.toUpperCase()) {
        ctx.body = {
            code: 0,
            msg: "验证码不一致"
        }
        return;
    }

    // 全部满足条件则登录
    let res = await global.query(`select * from user where name = '${name}' and pwd = '${pwd}'`)

    // 创建token令牌
    let token = jwt.sign({
        id: res[0].id,
        name: res[0].name,
    }, 'byp', { expiresIn: '1h' })

    // 返回登录成功
    if (res.length > 0) {
        ctx.body = {
            code: 3,
            msg: '登录成功！',
            uid: res[0].id,
            token
        }
    } else {
        ctx.body = {
            code: 4,
            msg: '登录失败！',
        }
    }
})

// 注册
router.post('/register', async (ctx) => {
    let { name, pwd } = ctx.request.body; // 获取参数

    // 判断该用户是否存在
    let result = await global.query(`select * from user where name = '${name}'`)
    if (result.length == 1) {
        ctx.body = {
            code: 5,
            msg: '用户已存在！'
        }
        return;
    }

    // 不存在则注册
    let res = await global.query(`insert into user(name,pwd) values ('${name}','${pwd}')`)
    if (res.affectedRows == 1) {
        ctx.body = {
            code: 6,
            msg: '注册成功！'
        }
    } else {
        ctx.body = {
            code: 7,
            msg: '注册失败！'
        }
    }
})

// 注册成功之后接着登录

// 获取左侧列表
router.get('/list', async ctx => {
    let res = await global.query(`select * from list`)
    ctx.body = {
        code: 1,
        msg: '获取成功',
        data: res,
    }
})

// 获取右侧列表
router.post('/list/right', async ctx => {
    let { id } = ctx.request.body

    let res = await global.query(`select * from context where pid = ${id} `)
    ctx.body = {
        code: 1,
        msg: '获取成功',
        data: res,
    }
})

// 获取某一条数据
router.post('/list/item', async ctx => {
    let { id } = ctx.request.body

    let res = await global.query(`select * from context where id = ${id} `)
    ctx.body = {
        code: 1,
        msg: '获取成功',
        data: res,
    }
})

// 获取所有数据
router.get('/alllist', async ctx => {
    let res = await global.query(`select * from context`)
    ctx.body = {
        code: 1,
        msg: '获取成功',
        data: res
    }
})

// 获取购物车数据
router.post('/getcarlist', async ctx => {
    let res = await global.query(`select * from carlist`)

    ctx.body = {
        code: 1,
        msg: '获取成功',
        data: res
    }
})

// 添加到购物车
router.post('/addcar', async ctx => {
    let { name, price, nums = 1, img } = ctx.request.body

    let ress = await global.query(`select * from carlist where name = '${name}'`)
    ctx.body = {
        code: 1,
        msg: "搜索成功",
        data: ress
    }
    if (ress.length == 0) {
        let res = await global.query(`insert into carlist(name,price,nums,img) values('${name}','${price}',${nums},'${img}')`)
    } else {
        let result = await global.query(`select * from carlist where name = '${name}'`)
        let nums = result[0].nums += 1
        let res = await global.query(`update carlist set nums = ${nums} where name = '${name}'`)
        ctx.body = { code: 2, msg: '修改成功' }
    }
})

// 加加
router.post('/addnums', async ctx => {
    let { name } = ctx.request.body

    let result = await global.query(`select * from carlist where name = '${name}'`)
    let nums = result[0].nums += 1
    let res = await global.query(`update carlist set nums = ${nums} where name = '${name}'`)
    ctx.body = { code: 2, msg: '修改成功' }
})

// 减减
router.post('/jiannums', async ctx => {
    let { name } = ctx.request.body

    let result = await global.query(`select * from carlist where name = '${name}'`)
    let nums = result[0].nums -= 1
    let res = await global.query(`update carlist set nums = ${nums} where name = '${name}'`)
    if (result[0].nums < 1) {
        let res = await global.query(`delete from carlist where name = '${name}'`)
    }
    ctx.body = { code: 2, msg: '修改成功' }
})

// 搜索
router.post('/search', async ctx => {
    let { name } = ctx.request.body

    let res = await global.query(`select * from context where name like '%${name}%'`)
    ctx.body = {
        code: 1,
        msg: '搜索成功',
        data: res
    }
})

app.use(cors())
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(4000, () => {
    console.log("http://localhost:4000 后台服务器启动成功");
});